package com.example.blog.controller.admin;

import com.example.blog.pojo.Picture;
import com.example.blog.service.PictureService;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;

/**
 * @version 1.0
 * @author: admin
 * @date: 2020/9/5
 */
@Controller
@RequestMapping("/admin")
public class PictureController {
    private final static String PICTURE_PAGE = "admin/pictures";
    private final static String PICTURE_PAGE_INPUT = "admin/pictures-input";
    @Resource
    private PictureService pictureService;
    @GetMapping("/pictures")
    public String toPicture(Integer id, Model model){
        PageInfo<Picture> pageInfo = pictureService.getAllPicture(id, 7);
        model.addAttribute("pageInfo",pageInfo);
        return PICTURE_PAGE;
    }
    @PostMapping("/picture/save")
    public String savePicture(Picture picture, RedirectAttributes redirectAttributes){
        String message = "操作成功！";
        try {
            pictureService.savePicture(picture);
        } catch (Exception e) {
            message = "保存失败，出现异常！";
        }
        redirectAttributes.addAttribute("message",message);
        return "redirect:/admin/pictures";
    }
    @GetMapping("/picture/{id}/input")
    public String toPictureInput(@PathVariable Long id, Model model){
        Picture picture = new Picture();
        if (id > 0) {
            picture = pictureService.getPictureById(id);
        }
        model.addAttribute("picture",picture);
        return PICTURE_PAGE_INPUT;
    }
    @GetMapping("/picture/{id}/delete")
    public String toPictureDelete(@PathVariable Long id, RedirectAttributes redirectAttributes){
        String message = "操作成功！";
        try {
            pictureService.delPicture(id);
        } catch (Exception e) {
            message = "保存失败，出现异常！";
        }
        redirectAttributes.addAttribute("message",message);
        return "redirect:/admin/pictures";
    }
}
